<?php
/*
 * module blog
 */
class mod_blognew extends module{
    #tables
    private $table_section = "mod_blognew_section";
    private $table_article = "mod_blognew_article";
    private $table_comment = "mod_blognew_comment";
    private $table_options = "mod_blognew_options";

    private $articles_per_page = 10;
    private $user_group;
    private $sec = array();
    private $com_tree = array();
    private $comments_by_levels = true;


    public function init(){
        $this->articles_per_page = $this->api->dbo->select($this->table_options,"articles_per_page","limit 1 offset 0",_RESULT_SINGLE);
        $this->comments_by_levels = $this->api->dbo->select($this->table_options,"comments_by_levels","limit 1 offset 0",_RESULT_SINGLE);
    }

    public function defaultaction(){

    }

    //SECTIONS

    private function addsection(){
    #add new section
    if($this->api->user->GetUserGroup()!=1)
            return null;
    if(isset($_POST["sect_name"])&&(!empty($_POST["sect_name"]))){
        $s_name = $_POST["sect_name"];
        if($this->api->dbo->select($this->table_section,"sect_id","WHERE sect_name='".$s_name."'",_RESULT_BOOL))
           return $this->api->message($this->lang->get("s7")).$this->api->base->buildactionlink("viewsections","",$this->lang->get("s5")).$this->api->base->htmlactionlink("addsection","",$this->lang->get("s6"));
        if(!$this->api->dbo->insert($this->table_section,array("sect_name"=>$s_name)))
            return $this->api->error($this->lang->get("s4"));
    }
    if(isset($_GET["addsection"]))
       return $this->api->view->template("addsection");
    return null;
    }

    private function deletesection(){
        if($this->api->user->GetUserGroup()!=1)
                return null;
        //echo $_GET["section"];
        $section_id = $_GET["del_section_id"];
       // $section_id = $this->api->dbo->select($this->table_section,"sect_id","WHERE sect_name = '$section' limit 1 offset 0",_RESULT_SINGLE);
        $art_id = $this->api->dbo->select($this->table_article,"art_id","WHERE sect_id = '$section_id'",_RESULT_LIST);
        foreach($art_id as $val)
            $this->api->dbo->delete($this->table_comment,"WHERE art_id = '$val'");
        $this->api->dbo->delete($this->table_article,"WHERE sect_id = '$section_id'");
        $this->api->dbo->delete($this->table_section,"WHERE sect_id = '$section_id'");
        $this->sec = $this->api->dbo->select($this->table_section,"*","",_RESULT_ASSOC);
        return null;
    }

    public function viewsections(){
       #show sections
        if(isset($_GET["addsection"]))
            if(isset($_POST["sect_name"]))
            $this->addsection();
            else
            return $this->addsection();
        
        if(isset($_GET["del_section_id"]))
            $this->deletesection();
        $this->sec = $this->api->dbo->select($this->table_section,"*","",_RESULT_ASSOC);
        $gr = $this->api->user->GetUserGroup();
        return $this->api->view->template("viewsections",array("sections"=>&$this->sec,"group"=>&$gr));
    }

    //ARTICLES

    private function getartlist($sect,$offset){
        if($sect==null)
            return $this->api->dbo->select($this->table_article,"*","limit $this->articles_per_page offset 0",_RESULT_ASSOC);
        else{
            return $this->api->dbo->select($this->table_article,"*","WHERE sect_id = '$sect' limit $this->articles_per_page offset $offset",_RESULT_ASSOC);
        }
    }

    public function articleslist(){
        if(isset($_GET["viewart_id"])||isset($_GET["addart_section_id"])||isset($_POST["addart_section_id"])||isset($_GET["upart_id"])||isset($_POST["upart_id"]))
            return null;
        if(isset($_POST["key"]))
            if($_POST["key"]!=="")
                return null;
        if(isset($_GET["delart_id"]))
            $this->deletearticle();
        if(isset($_GET["page"]))
           $pages = $_GET["page"];
        else
            $pages = 0;
        $offset = $pages*$this->articles_per_page;
        if(isset($_GET["artl_section"]))
           $sect = $_GET["artl_section"];
        else
            $sect = null;
       $art = $this->getartlist($sect,$offset);
       if($sect==null){
           $sec = $this->lang->get("a4");
           for($i = 0;$i<count($art);$i++){
               $val = $art[$i]["sect_id"];
               $art[$i]["sect_name"] = $this->api->dbo->select($this->table_section,"sect_name","WHERE sect_id = '$val' limit 1 offset 0",_RESULT_SINGLE);
           }
       }
       else{
           for($i = 0;$i<count($art);$i++)
               $art[$i]["sect_name"] = "";
           $sec = $this->api->dbo->select($this->table_section,"sect_name","WHERE sect_id = '$sect' limit 1 offset 0",_RESULT_SINGLE);
       }
       $ar = $this->api->dbo->select($this->table_article,"art_id","",_RESULT_LIST);
       $accss = $this->api->user->GetUserGroup();
       $cnt = count($ar);
       if($sect!=null)
           $cnt = (int)$cnt%(int)$this->articles_per_page == 0?(int)$cnt/(int)$this->articles_per_page:(int)($cnt-(int)$cnt%(int)$this->articles_per_page)/(int)$this->articles_per_page+1;
       else
           $cnt=0;
       echo $this->api->view->template("articleslist",array("art"=>&$art,"sec"=>&$sec,"gr"=>&$accss));
       return $this->api->tools->pages("articleslist",$cnt,$pages);
    }
    
    public function addarticle(){
        if($this->api->user->GetUserGroup()!=1)
                return null;
        if(isset($_POST["addart_section_id"])){
            if(empty($_POST["art_title"])){
                print $this->api->message($this->lang->get("a5"));
                $section_id = $_POST["addart_section_id"];
                $tinymce = $this->api->libload("tinymce");
                $tinymce->set(_TINYMCE_FULL);
                return $this->api->view->template("addarticle",array("sect"=>$section_id));
            }
            $section_id = $_POST["addart_section_id"];
            $articles = $this->api->dbo->select($this->table_article,"art_name","WHERE sect_id = '$section_id'",_RESULT_LIST);
            if(in_array($_POST["art_title"],$articles)){
                return $this->api->view->template("addarticle",array("sect"=>&$section_id)). $this->api->message($this->lang->get("a9"));
            }
            $title = $_POST["art_title"];
            $head = $_POST["art_head"];
            $body = $_POST["art_body"];
            $ar = array("art_name"=>$title,"head"=>$head,"body"=>$body,"sect_id"=>$section_id,"created"=>date("Y-m-d H:i:s"),"updated"=>date("Y-m-d H:i:s"));
            if($this->api->dbo->insert($this->table_article,$ar)){
               print $this->api->message($this->lang->get("a2"));
               return $this->api->base->buildactionlink("articleslist","artl_section=".$section_id,$this->lang->get("a3"));
            }
        }
        if(isset($_GET["addart_section_id"])){
            $sect = $_GET["addart_section_id"];
            $tinymce = $this->api->libload("tinymce");
            $tinymce->set(_TINYMCE_FULL);
            return $this->api->view->template("addarticle",array("sect"=>$sect));
        }
        return null;
    }

    public function updatearticle(){
        if($this->api->user->GetUserGroup()!=1)
                return null;
        if(!isset($_GET["upart_id"]))
            return null;
        if(isset($_POST["upart_submit"])){
            $head = $_POST["up_head"];
            $body = $_POST["up_body"];
            $date = date("Y-m-d H:i:s");
            $id = $_POST["up_id"];
            if($this->api->dbo->update($this->table_article,"set head='$head', body='$body', updated = '$date' where art_id='$id'")){
                print $this->api->message($this->lang->get("a14"));
                return $this->api->base->buildactionlink("viewarticle","viewart_id=".$id,$this->lang->get("a10"));
            }
            else{
                print $this->api->error($this->lang->get("a11"));
                print $this->api->base->buildactionlink("updatearticle","upart_id=".$id,$this->lang->get("a12"));
                return $this->api->base->buildactionlink("viewarticle","viewart_id=".$id,$this->lang->get("a10"));
            }
        }
        $id = $_GET["upart_id"];
        $head = $this->api->dbo->select($this->table_article,"head","WHERE art_id='".$id."' limit 1 offset 0",_RESULT_SINGLE);
        $body = $this->api->dbo->select($this->table_article,"body","WHERE art_id='".$id."' limit 1 offset 0",_RESULT_SINGLE);
        $t = $this->api->libload("tinymce");
        $t->set(_TINYMCE_FULL);
        $name = $this->api->dbo->select($this->table_article,"art_name","WHERE art_id='$id' limit 1 offset 0",_RESULT_SINGLE);
        return $this->api->view->template("updatearticle",array("id"=>&$id,"name"=>&$name,"head"=>&$head,"body"=>&$body));
    }
    
    private function deletearticle(){
        if($this->api->user->GetUserGroup()!=1)
                return null;
        $id = $_GET["delart_id"];
        $this->api->dbo->delete($this->table_comment,"WHERE art_id = '$id'");
        if(!$this->api->dbo->delete($this->table_article,"WHERE art_id = '$id'")){
            return $this->api->error($this->lang->get("a15"));
        }
    }
    
    public function viewarticle(){
        if(!isset($_GET["viewart_id"]))
            return null;
        if(isset($_POST["key"]))
            if($_POST["key"]!="")
                return null;
        $id = $this->api->escapestring($_GET["viewart_id"]);
        $art = $this->api->dbo->select($this->table_article,"*","WHERE art_id = '$id' limit 1 offset 0",_RESULT_ROW);
        print $this->api->view->template("viewarticle",array("data"=>&$art))."\n";
        $this->addcomment();
        $this->deletecomment();
        return $this->viewcomments($id);
    }

    //COMMENTS

    private function viewcomments($id){
        //$com_lst = $this->api->dbo->select($this->table_comment,"*","WHERE art_id = '$id'",_RESULT_ASSOC);
        $com_lst = $this->createlist($id);
        if(isset($_GET["parent_id"]))
            $par = $_GET["parent_id"];
        else
            $par = -1;
        print "<div class=title>".$this->lang->get("c3")."</div>";
        if((count($com_lst)==0)&&($this->api->user->GetUserGroup())>0)
           return $this->api->view->template("addcomment",array("art_id"=>&$id,"parent"=>&$par));
        $gr = $this->api->user->GetUserGroup();
        //var_dump($com_lst);
        return $this->printcomments($com_lst, $par, $id);
    }

    private function &printcomments(array &$com, $par, $art_id){
        if(count($com)==0){
            $data=$this->lang->get("c6");
            return $data;
        }
        $data = "";
        $tiny = $this->api->libload("tinymce");
        $tiny->set(_TINYMCE_SIMPLE);
        $data.="<ul>";
        $user = $this->api->dbo->select("users","firstname, lastname","WHERE id=".$com[0]["user_id"],_RESULT_ASSOC);
        $data.="<div>".$user[0]["firstname"]." ".$user[0]["lastname"]."</div>";
        $data.="<div>".$com[0]["comment"]."</div>";
        $data.="<div>".$com[0]["added"]."</div>";
        if(($par==$com[0]["com_id"])&&($this->api->user->GetUserGroup()>0))
            $data.= $this->api->view->template("addcomment",array("parent"=>&$par,"art_id"=>&$art_id));
        else
             if(($this->api->user->GetUserID()==$com[0]["user_id"])||($this->api->user->GetUserGroup()==1))
                 $data.="<div>".$this->api->base->buildactionlink("viewarticle","viewart_id=".$art_id."&delcom_id=".$com[0]["com_id"],$this->lang->get("c5"))."</div>";
          else
             if($this->api->user->GetUserGroup()>0)
                     $data.="<div>".$this->api->base->buildactionlink("viewarticle","viewart_id=".$art_id."&parent_id=".$com[0]["com_id"],$this->lang->get("c4"))."</div>";
        if(count($com)>1){
            for($i=1;$i<count($com);$i++){
                if($com[$i-1]["level"]<$com[$i]["level"])
                    $data.="<ul>";
                $user = $this->api->dbo->select("users","firstname, lastname","WHERE id=".$com[$i]["user_id"],_RESULT_ASSOC);
                $data.="<div>".$user[0]["firstname"]." ".$user[0]["lastname"]."</div>";
                $data.="<div>".$com[$i]["comment"]."</div>";
                $data.="<div>".$com[$i]["added"]."</div>";
                if(($par==$com[0]["com_id"])&&($this->api->user->GetUserGroup()>0))
                    $data.= $this->api->view->template("addcomment",array("parent"=>&$par,"art_id"=>&$art_id));
                else{
                    if(($this->api->user->GetUserID()==$com[$i]["user_id"])||($this->api->user->GetUserGroup()==1))
                       $data.="<div>".$this->api->base->buildactionlink("viewarticle","viewart_id=".$art_id."&delcom_id=".$com[$i]["com_id"],  $this->lang->get("c5"))."</div>";
                    else
                     if($this->api->user->GetUserGroup()>0)
                        $data.="<div>".$this->api->base->buildactionlink("viewarticle","viewart_id=".$art_id."&parent_id=".$com[$i]["com_id"],$this->lang->get("c4"))."</div>";
                }
                $cnt = $i==count($com)-1?$com[$i]["level"]:$com[$i]["level"]-$com[$i+1]["level"];
                if($cnt>0)
                    for($j=1;$j<=$cnt;$j++)
                        $data.="</ul>";
            }
        }
       $data.="</ul>";
        if(($par == -1)&&($this->api->user->GetUserGroup()>0))
            $data.= $this->api->view->template("addcomment",array("parent"=>&$par,"art_id"=>&$art_id));
        return $data;
    }
    
    private function buildtree($parent, $level, $art){
        static $cnt = 0;
        if(!$this->api->dbo->select($this->table_comment,"*","WHERE parent_id = '".$parent."'and art_id = '".$art."'",_RESULT_BOOL))
                return;
        $this->com_tree[$level] = $this->api->dbo->select($this->table_comment,"*","WHERE parent_id = '".$parent."'and art_id = '".$art."'",_RESULT_ASSOC);
        for($i=0; $i<count($this->com_tree[$level]); $i++){
            $this->com_tree[$level][$i]["numb"] = $cnt;
            $cnt++;
            $this->buildtree($this->com_tree[$level][$i]["com_id"], $level+1, $art);
        }
        return;
    }

    private function &createlist($art){
        $this->buildtree(-1, 0,$art);
        $res = array();
        foreach($this->com_tree as $lev=>$value){
                foreach($value as $val){
                    $res[$val["numb"]] = $val;
                    $res[$val["numb"]]["level"] = $lev;
                }
        }
        return $res;
    }

    private function addcomment(){
        if(!isset($_POST["add_comment"]))
            return null;
        $data = array("user_id"=>$this->api->user->GetUserID(),"art_id"=>$_POST["addcom_art_id"],"parent_id"=>$_POST["parent_id"],"comment"=>$_POST["comment"],"added"=>date("Y-m-d H:i:s"));
        if(!$this->api->dbo->insert($this->table_comment,$data))
                return $this->api->error($this->lang->get("a11"));
        return null;
    }

    private function deletecomment(){
        if(!isset($_GET["delcom_id"]))
            return null;
        if(($this->api->user->GetUserID()!=$this->api->dbo->select($this->table_comment,"user_id","WHERE com_id='".$_GET["delcom_id"]."' limit 1 offset 0",_RESULT_SINGLE))&&($this->api->user->GetUserGroup()!=1))
                return null;
        $id = $_GET["delcom_id"];
        $art = $this->api->dbo->select($this->table_comment,"art_id","WHERE com_id = '$id'",_RESULT_SINGLE);
        $this->buildtree($id,0,$art);
        $this->api->dbo->delete($this->table_comment,"WHERE com_id =".$id);
        foreach($this->com_tree as $value)
                foreach($value as $val)
                    $this->api->dbo->delete($this->table_comment,"WHERE com_id =".$val["com_id"]);
        //        return $this->api->error($this->lang->get("c1"));
    }

    //SEARCH

    public function search(){
       /* if(!$this->api->checkPOST("search"))
                return $this->api->view->template("search");
        if(isset($_POST["key"]))
            if($_POST["key"]=="")
                return $this->api->view->template("search");
            else
                 $this->api->base->callaction("blognew","printresults");
        return $this->api->view->template("search");*/
        return $this->api->view->template("search");
    }

    public function printresults(){
        if(!isset($_POST["key"]))
            return null;
        $key = $_POST["key"];
        $art = $this->api->dbo->select($this->table_article,"*");
        $results = array();
        for($i=0;$i<count($art);$i++){
            if(preg_match('/'.$key.'/i',$art[$i]["art_name"])){
                    //str_replace($key,"<B>".$key."</B>",$art[$i]["art_name"]);
                $results[] = $art[$i];
                continue;
                }
            if(preg_match('/'.$key.'/i',$art[$i]["head"])){
               // str_replace($key,"<i>".$key."</i>",$art[$i]["head"]);
                $results[] = $art[$i];
                continue;
            }
            if(preg_match('/'.$key.'/i',$art[$i]["body"])){
                    //str_replace($key,"<B>".$key."</B>",$art[$i]["body"]);
                $results[] = $art[$i];
                continue;
            }
        }
        //var_dump($this->search_results);
        if(count($results)==0)
            return $this->lang->get("f3");
        for($i=0;$i<count($results);$i++)
            $results[$i]["sect_name"] = $this->api->dbo->select($this->table_section,"sect_name","WHERE sect_id = '".$results[$i]["sect_id"]."'",_RESULT_SINGLE);
        $sec = $this->lang->get("f2");
        $group = $this->api->user->GetUserGroup();
        return $this->api->view->template("articleslist",array("sec"=>&$sec,"gr"=>&$group,"art"=>&$results));
    }

    public function adminka(){
        $art = $this->articles_per_page;
        if(!isset($_POST["opt_submit"]))
            return $this->api->view->template("adminka",array("art"=>&$art));
        $art = $_POST["artperpage"];
        $com = $_POST["com"];
        if($this->api->dbo->update($this->table_options,"SET articles_per_page='$art', comments_by_levels='$com' WHERE id='1'")){
                return $this->api->message($this->lang->get("o7"));
                }
    }

    public function install(){
        $table = new sqltable($this->table_section);
        $table->addfield("sect_id",_FIELD_INTAUTO);
        $table->addfield("sect_name",_FIELD_TEXT);
        $table->addkey(_KEY_PRIMARY,"sect_id");
        $this->api->dbo->createtable($table);
        unset($table);

        $table = new sqltable($this->table_article);
        $table->addfield("art_id",_FIELD_INTAUTO);
        $table->addfield("art_name",_FIELD_TEXT);
        $table->addfield("head",_FIELD_LONGTEXT);
        $table->addfield("body",_FIELD_LONGTEXT);
        $table->addfield("created",_FIELD_DATETIME);
        $table->addfield("updated",_FIELD_DATETIME);
        $table->addfield("sect_id",_FIELD_INT);
          $table->addkey(_KEY_PRIMARY,"art_id");
        $this->api->dbo->createtable($table);
        unset($table);

        $table = new sqltable($this->table_comment);
        $table->addfield("com_id",_FIELD_INTAUTO);
        $table->addfield("user_id",_FIELD_INT);
        $table->addfield("art_id",_FIELD_INT);
        $table->addfield("parent_id",_FIELD_INT);
        $table->addfield("comment",_FIELD_TEXT);
        $table->addfield("added",_FIELD_DATETIME);
          $table->addkey(_KEY_PRIMARY,"com_id");
        $this->api->dbo->createtable($table);

        $table = new sqltable($this->table_options);
        $table->addfield("articles_per_page",_FIELD_INT);
        $table->addfield("comments_by_levels",_FIELD_BOOL);
        $table->addfield("id",_FIELD_INTAUTO);
        $table->addkey(_KEY_PRIMARY,"id");
        $this->api->dbo->createtable($table);

        $this->api->dbo->insert($this->table_options,array("articles_per_page"=>10,"comments_by_levels"=>true));
    }

    public function uninstall(){

    }

}
?>
